package com.itheima.gatewayadmin.filter;


import com.itheima.common.constants.SystemConstants;
import com.itheima.common.util.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
@Slf4j
public class AuthorizeFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求对象
        ServerHttpRequest req = exchange.getRequest();
        //获取响应对象
        ServerHttpResponse res = exchange.getResponse();
        //1.获取请求路径
        String path = req.getURI().getPath();
        log.info("请求了路径：{}",path);

        //2.判断是否是白名单（登录请求，获取验证码请求）
        //LoginController, 退出。。。等 是不需要登录都可以完成的
        if (path.startsWith("/admin/login")){
            //放行
            return chain.filter(exchange);
        }
        //3.非名单：获取请求头信息token信息
        String token = req.getHeaders().getFirst("token");
        //4.如果没有token值，则返回401，返回前端登录
        //5.有值
        if (!StringUtils.isEmpty(token)){
            //校验token的有效性
            if (SystemConstants.JWT_OK== AppJwtUtil.verifyToken(token)){
              //6.通过，放行
                return chain.filter(exchange);
            }

        }
        //7.返回401,重新登录  (401代表未登录)
        res.setStatusCode(HttpStatus.UNAUTHORIZED);
        return res.setComplete();
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
